package com.shixianjun.sort;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class SortableElement {

    public int id;
    public int value;

    public SortableElement(int _id, int _value) {
        id = _id;
        value = _value;
    }

    public static SortableElement[] randomSortableElementArray(int length, int maxValue, boolean repeatable) {

        int[] arrNums = new int[length];
        if (repeatable) {
            for (int i = 0; i < length; i++) {
                arrNums[i] = (int) (Math.random() * maxValue) + 1;
            }
        } else {
            if (maxValue < length) {
                System.out.print("⚠️不可重复时，最大值不可以小于长度，最大值已更改为长度值！\n");
                maxValue = length;
            }
            Set<Integer> set = new HashSet<Integer>();
            while (set.size() < length) {
                set.add((int) (Math.random() * maxValue) + 1);
            }
            Integer[] arrTemporary = new Integer[set.size()];
            set.toArray(arrTemporary);
            arrNums = Arrays.stream(arrTemporary).mapToInt(Integer::intValue).toArray();
        }

        SortableElement[] arrElements = new SortableElement[length];
        for (int i = 0; i < length; i++) {
            arrElements[i] = new SortableElement(i, arrNums[i]);
        }

        return arrElements;
    }

    public static void printSortableElementArray(String title, SortableElement[] arr) {
        System.out.print(title + ": ");
        for (int i = 0; i < arr.length; i++) {
            System.out.printf(" %02d", arr[i].value);
        }
        System.out.print("\n");
    }
}